<template>
  <div>
    <!--======================================搜索栏======================================================-->

    <el-card shadow="never" class="search-card">
      <el-row :gutter="20" class="el-row">
        <el-col class="button-box" :span="4">
          <el-input
            v-model="queryVo.query.queryInfo"
            size="small"
            class="search-input"
            placeholder="请输入搜索内容"
            clearable
            @clear="handleClear('queryInfo')"
          />
        </el-col>
        <el-col class="button-box" :span="4.5">
          <div>
            单位名称：
            <el-select
              v-model="queryVo.query.unitId"
              size="small"
              class="unit-selector"
              clearable
              placeholder="单位名称"
              @clear="handleClear('unitId')"
            >
              <el-option
                v-for="item in unitList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>

        </el-col>
        <el-col class="button-box" :span="5" />

        <el-col class="button-box" :span="6">
          <div>
            人员状态：
            <el-select
              v-model="tempStatusList"
              size="small"
              class="selector"
              multiple
              clearable
              value-key="label"
              placeholder="请选择"
              @clear="handleClear('statusList')"
              @change="updateStatusList"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

        </el-col>
        <el-col :offset="3" :span="5">
          <div style="float: right">
            <el-button
              size="small"
              type="primary"
              plain
              @click="handleSearch"
            >搜索</el-button>

            <el-button
              size="small"
              type="primary"
              plain
              @click="resetQueryVo"
            >重置</el-button>

            <el-button
              size="small"
              type="primary"
              plain
              @click="unfold = !unfold"
            >{{ unfold === false ? '更多' : '收起' }}</el-button>

          </div>

        </el-col>
      </el-row>

      <div v-if="unfold">
        <el-row v-if="unfold" :gutter="20" class="extend-row">
          <el-col class="button-box" :span="4.5">
            <div>
              工号：
              <el-input
                v-model="queryVo.query.id"
                size="small"
                class="search-input"
                placeholder="请输入搜索内容"
                clearable
                @clear="handleClear('id')"
              />
            </div>

          </el-col>

          <el-col class="button-box" :span="4.5">
            <div>
              姓名：
              <el-input
                v-model="queryVo.query.name"
                size="small"
                class="search-input"
                placeholder="请输入搜索内容"
                clearable
                @clear="handleClear('name')"
              />
            </div>

          </el-col>

          <el-col class="button-box" :span="4.5">
            <div>
              手机号：
              <el-input
                v-model="queryVo.query.phone"
                size="small"
                class="search-input"
                placeholder="请输入搜索内容"
                clearable
                @clear="handleClear('phone')"
              />
            </div>

          </el-col>

          <el-col class="button-box" :span="4.5">
            <div>
              账号：
              <el-input
                v-model="queryVo.query.username"
                size="small"
                class="search-input"
                placeholder="请输入搜索内容"
                clearable
                @clear="handleClear('username')"
              />
            </div>

          </el-col>

        </el-row>

      </div>
    </el-card>

    <!--====================================END=========================================================-->

    <!--======================================表格======================================================-->

    <el-card shadow="never" class="device-table-card">
      <el-button
        size="small"
        type="primary"
        @click="handleCreate"
      >添加实验室管理员</el-button>

      <el-table
        ref="filterTable"
        :data="managerList"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="编号"
          width="100"
        />
        <el-table-column
          prop="name"
          label="名称"
          width="100"
        />

        <el-table-column
          prop="phone"
          label="手机号"
          width="150"
        />

        <el-table-column
          prop="unit"
          label="所属单位"
          width="180"
        />

        <el-table-column
          prop="username"
          label="账号"
          width="180"
        />

        <el-table-column
          prop="status"
          label="状态"
          width="100"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === 1 ? 'primary' : 'success'"
              disable-transitions
            >
              {{ scope.row.status === 1 ? "在职" : "出差" }}
            </el-tag>

          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" size="mini" @click=" handleUpdate(scope.row)">修改</el-button>
            <!-- 删除 -->
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>

          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="queryVo.pageNum"
        :page-sizes="[1, 2, 5, 100]"
        :page-size="queryVo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!--====================================END=========================================================-->

    <!--======================================表单======================================================-->

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :append-to-body="true"
    >
      <el-form
        ref="dataForm"
        :rules="formRules"
        :model="temp"
        label-width="80px"
      >

        <el-form-item prop="id" label="工号">
          <el-input v-model="temp.id" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="name" label="姓名">
          <el-input v-model="temp.name" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="username" label="账号">
          <el-input v-model="temp.username" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="password" label="密码">
          <el-input v-model="temp.password" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="phone" label="手机号">
          <el-input v-model="temp.phone" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="unitId" label="单位：">
          <el-select
            v-model="temp.unitId"
            size="small"
            class="unit-selector"
            value-key="label"
            placeholder="单位名称"
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="status" label="状态">
          <el-radio-group v-model="temp.status" size="medium">
            <el-radio border :label="1">在职</el-radio>
            <el-radio border :label="0">出差</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createLabManager():updateLabManager()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!--====================================END=========================================================-->

  </div>
</template>

<script>
import { getUnitList } from '@/api/unit'
import { addLabManager, deleteLabManager, getLabManagerList, updateLabManager } from '@/api/labManager'
import checkPermission from '@/utils/permission'

export default {
  name: 'LabManagerTable',
  data() {
    return {
      isAdmin: checkPermission(['admin']),
      totalCount: 5,
      queryVo: {
        query: {
          queryInfo: null,
          id: null,
          name: null,
          unitId: null,
          username: null,
          password: null,
          phone: null,
          statusList: null
        },
        pageNum: 1,
        pageSize: 5
      },

      unfold: true,

      tempStatusList: [],

      statusOptions: [{
        label: '出差',
        value: 0
      },
      {
        label: '在职',
        value: 1
      }
      ],

      textMap: {
        update: '修改',
        create: '添加'
      },

      managerList: [],

      unitList: [],

      labList: [],

      dialogFormVisible: false,

      dialogStatus: '',

      temp: {
        id: '',
        name: '',
        unit: '',
        username: '',
        password: '',
        phone: '',
        status: ''
      },

      formRules: {
        id: [
          { required: true, message: '请输入工号', trigger: 'blur' }

        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }

        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }

        ],
        phone: [
          {
            pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/,
            message: '手机号格式错误',
            trigger: 'blur'
          },
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
          }

        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' }

        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }

        ]
      }

    }
  },

  watch: {
    tempStatusList(val) {
      if (val.length === 0) {
        this.queryVo.query.statusList = null
      }
    }
  },

  mounted() {
    getLabManagerList(this.queryVo).then(response => {
      this.managerList = response.data.list
      this.totalCount = response.data.total
    })

    getUnitList(this.queryVo).then(response => {
      this.unitList = response.data.list
    })
  },
  methods: {
    /* ==========================================搜索相关===================================================*/

    handleSearch() {
      getLabManagerList(this.queryVo).then(response => {
        this.managerList = response.data.list
        this.totalCount = response.data.total
      })
    },

    handleClear(queryParam) {
      this.queryVo.query[queryParam] = null
    },

    resetQueryVo() {
      this.queryVo.query = {
        queryInfo: null,
        id: null,
        name: null,
        unitId: null,
        username: null,
        password: null,
        phone: null,
        statusList: null
      }
      this.tempStatusList = []
    },

    updateStatusList() {
      this.queryVo.query.statusList = this.tempStatusList
    },

    /* ==========================================END===================================================*/

    /* ==========================================表单相关===================================================*/

    resetTemp() {
      this.temp = {
        id: '',
        name: '',
        unitId: '',
        username: '',
        status: ''
      }
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createLabManager() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addLabManager(this.temp).then(() => {
            getLabManagerList(this.queryVo).then(response => {
              this.managerList = response.data.list
              this.totalCount = response.data.total
            })

            this.dialogFormVisible = false

            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateLabManager() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateLabManager(tempData).then(() => {
            getLabManagerList(this.queryVo).then(response => {
              this.managerList = response.data.list
              this.totalCount = response.data.total
            })

            this.dialogFormVisible = false

            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleDelete(row) {
      this.$confirm('此操作将永久删除该实验室管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLabManager(row.id).then(() => {
          getLabManagerList(this.queryVo).then(response => {
            this.labManagerList = response.data.list
            this.totalCount = response.data.total
          })

          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    /* ==========================================END===================================================*/

    /* ==========================================分页相关===================================================*/

    handleSizeChange(newSize) {
      this.queryVo.pageSize = newSize
      getLabManagerList(this.queryVo).then(response => {
        this.managerList = response.data.list
        this.totalCount = response.data.total
      })
    },
    handleCurrentChange(newSize) {
      this.queryVo.pageNum = newSize
      getLabManagerList(this.queryVo).then(response => {
        this.managerList = response.data.list
        this.totalCount = response.data.total
      })
    }

    /* ==========================================END===================================================*/

  }
}
</script>

<style scoped>

.search-input {
  width: 150px;
}
.selector {
  width: 130px;
}
.lab-selector {
  width: 150px;
}
.unit-selector {
  width: 150px;
}
.search-card {
  font-size: 15px;
}
.extend-row{
  margin-top: 10px;
}
</style>
